 <?php

class Mapper {
    protected $here = null;
    protected $base = null;
    protected $routes = array();
	protected static $instance;
	
    public function __construct() {
        if (is_null($this->base)) {
            $this->base = dirname($_SERVER['PHP_SELF']);
            if ($this->base == DS || $this->base == '.') {
                $this->base = '/';
            }
        }
        if (is_null($this->here)) {
            $start = strlen($this->base);
            $this->here = self::normalize(substr($_SERVER['REQUEST_URI'], $start));
        }
    }

	public static function instance() {
		if (self::$instance === null) {
			$c = __CLASS__;
			self::$instance = new $c;
		}
		return self::$instance;
	}
	
    public static function first() {
		$base = explode('/', self::instance()->here);
		array_shift($base);
		return $base[0];
    }	
	
    public static function here() {
        return self::instance()->here;
    }

    public static function base() {
    	if (self::instance()->base == '/') {
    		return '';
    	}
        return self::instance()->base;
    }
    
    public static function normalize($url) {
        if (preg_match('/^[a-z]+:/', $url)) {
            return $url;
        }
        $url = '/' . $url;
        while (strpos($url, '//') !== false) {
            $url = str_replace('//', '/', $url);
        }
        $url = rtrim($url, '/');
        if (empty($url)) {
            $url = '/';
        }
        return $url;
    }
    
    public static function connect($url, $page = null) {
    	if (is_array($url)) {
    		foreach ($url as $key => $value) {
    			$arr = self::connect($key, $value);
    		}
    		return $arr;
    	}
    	self::instance()->routes[$url] = $page;
    }
    
    public static function routes() {
    	return self::instance()->routes;
    }
	
    public static function url() {
    	$url = array_diff(explode('/', self::here()), array(array_pop(explode('/', self::here()))));
    	$is_page = preg_match('/[0-9]+/', self::here());
    	return !$is_page ? str_replace(self::base(), '', self::here()) : str_replace(self::base(), '', implode('/', $url));
    }	
}

?>